package com.sky.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.commons.collections4.Get;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserSerrviceImpl implements UserService {

    public static final String RequestURL = "https://api.weixin.qq.com/sns/jscode2session";

    public static final String Grant_Type = "authorization_code";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 微信小程序用户登录业务
     * @param userLoginDTO
     * @return
     */
    public User wechatLogin(UserLoginDTO userLoginDTO) {
        //通过code向微信后端接口请求校验 获得openid等信息
        String openid = GetOpenId(userLoginDTO.getCode());

        //校验相应的openid对应的用户是否存在 以及openid是否为空->抛出异常
        if(openid == null) throw new LoginFailedException(MessageConstant.LOGIN_FAILED);

        //如果用户不存在 则创建该用户
        User user = userMapper.getUserByOpenId(openid);
        if(user == null){
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.insertUser(user);
        }

        //返回该用户对象即可
        return user;
    }

    /**
     * 将这个方法抽象出来 通过传入用户的授权码code获得相应的用户openid信息
     * 由于使用有限 设置为private 只在本类中可以使用即可
     * @param code
     * @return
     */
    private String GetOpenId(String code){
        Map<String,String> RequestMap = new HashMap<>();
        RequestMap.put("appid",weChatProperties.getAppid());
        RequestMap.put("secret",weChatProperties.getSecret());
        RequestMap.put("js_code",code);
        RequestMap.put("grant_type",Grant_Type);
        String response = HttpClientUtil.doGet(RequestURL, RequestMap);
        JSONObject jsonObject = JSON.parseObject(response);
        String openid = jsonObject.getString("openid");
        return openid;
    }

}
